﻿using Microsoft.Extensions.DependencyModel;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.Loader;
using Lrd.Template.Core.Infrastructure.Filter;

namespace Lrd.Template.Core.Infrastructure.Reflection
{
    /// <summary>
    /// 应用程序目录程序集查找器
    /// </summary>
    public class AppRuntimeAssemblyFinder : FinderBase<Assembly>, IAllAssemblyFinder
    {
        /// <summary>
        /// 获取项目程序集，排除所有的系统程序集(Microsoft.***、System.***等)、Nuget下载包
        /// </summary>
        /// <returns></returns>
        private IList<Assembly> GetAllAssemblies()
        {
            List<Assembly> list = new List<Assembly>();
            var deps = DependencyContext.Default;
            //排除所有的系统程序集、Nuget下载包
            var libs = deps.CompileLibraries.Where(lib => !lib.Serviceable && lib.Type != "package");

            try
            {
                foreach (var lib in libs)
                {
                    var assembly = AssemblyLoadContext.Default.LoadFromAssemblyName(new AssemblyName(lib.Name));
                    list.Add(assembly);
                }
            }
            catch (Exception ex)
            {

                throw ex;
            }
          
            return list;
        }

    

        //private IList<Type> GetAllTypes()
        //{
        //    List<Type> list = new List<Type>();
        //    foreach (var assembly in GetAllAssemblies())
        //    {
        //        var typeinfos = assembly.DefinedTypes;
        //        foreach (var typeinfo in typeinfos)
        //        {
        //            list.Add(typeinfo.AsType());
        //        }
        //    }
        //    return list;
        //}

 

        protected override Assembly[] FindAllItems()
        {
            return GetAllAssemblies().ToArray();
        }
    }
}
